#pragma once

#include <string>
#include <memory>
#include <unordered_map>
#include <mutex>
#include <shared_mutex>
#include <atomic>
#include <functional>
#include <chrono>
#include <vector>

// CTP API headers
#ifdef _WIN32
#include "ctp/windows64/ThostFtdcUserApiDataType.h"
#include "ctp/windows64/ThostFtdcUserApiStruct.h"
#include "ctp/windows64/ThostFtdcMdApi.h"
#include "ctp/windows64/ThostFtdcTraderApi.h"
#else
#include "ctp/linux64/ThostFtdcUserApiDataType.h"
#include "ctp/linux64/ThostFtdcUserApiStruct.h"
#include "ctp/linux64/ThostFtdcMdApi.h"
#include "ctp/linux64/ThostFtdcTraderApi.h"
#endif

#include "market_data.h"
#include "execution.h"
#include "data_manager.h"
#include "trade_data.h"

namespace hft {

// CTP配置结构
struct CTPConfig {
    std::string front_addr;    // 前置机地址
    std::string broker_id;     // 经纪商代�?
    std::string user_id;       // 用户代码
    std::string password;      // 密码
    std::string app_id;        // 应用标识
    std::string auth_code;     // 认证�?
};

// CTP行情回调�?
class CTPMdSpi : public CThostFtdcMdSpi {
public:
    explicit CTPMdSpi(CTPMarketDataHandler* handler) : handler_(handler) {}

    void OnFrontConnected() override {
        handler_->onConnected();
    }

    void OnFrontDisconnected(int nReason) override {
        handler_->onDisconnected(nReason);
    }

    void OnRspUserLogin(CThostFtdcRspUserLoginField* pRspUserLogin, 
                       CThostFtdcRspInfoField* pRspInfo, 
                       int nRequestID, 
                       bool bIsLast) override {
        if (pRspInfo && pRspInfo->ErrorID == 0) {
            handler_->onLoginSuccess();
        } else {
            handler_->onLoginFailed(pRspInfo ? pRspInfo->ErrorID : -1,
                                  pRspInfo ? pRspInfo->ErrorMsg : "Unknown error");
        }
    }

    void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField* pDepthMarketData) override {
        if (!pDepthMarketData) return;

        MarketDataMessage msg;
        msg.symbol = pDepthMarketData->InstrumentID;
        msg.last_price = pDepthMarketData->LastPrice;
        msg.volume = pDepthMarketData->Volume;
        msg.turnover = pDepthMarketData->Turnover;
        msg.open_interest = pDepthMarketData->OpenInterest;
        msg.bid_price = pDepthMarketData->BidPrice1;
        msg.bid_volume = pDepthMarketData->BidVolume1;
        msg.ask_price = pDepthMarketData->AskPrice1;
        msg.ask_volume = pDepthMarketData->AskVolume1;
        msg.timestamp = std::chrono::system_clock::now();

        handler_->onMarketData(msg);
    }

    void OnRspError(CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) override {
        if (pRspInfo) {
            handler_->onError(pRspInfo->ErrorID, pRspInfo->ErrorMsg);
        }
    }

private:
    CTPMarketDataHandler* handler_;
};

// CTP交易回调�?
class CTPTraderSpi : public CThostFtdcTraderSpi {
public:
    explicit CTPTraderSpi(CTPTraderHandler* handler) : handler_(handler) {}

    void OnFrontConnected() override {
        handler_->onConnected();
    }

    void OnFrontDisconnected(int nReason) override {
        handler_->onDisconnected(nReason);
    }

    void OnRspUserLogin(CThostFtdcRspUserLoginField* pRspUserLogin, 
                       CThostFtdcRspInfoField* pRspInfo, 
                       int nRequestID, 
                       bool bIsLast) override {
        if (pRspInfo && pRspInfo->ErrorID == 0) {
            handler_->onLoginSuccess();
        } else {
            handler_->onLoginFailed(pRspInfo ? pRspInfo->ErrorID : -1,
                                  pRspInfo ? pRspInfo->ErrorMsg : "Unknown error");
        }
    }

    void OnRtnOrder(CThostFtdcOrderField* pOrder) override {
        if (!pOrder) return;

        Order order;
        order.order_id = pOrder->OrderRef;
        order.symbol = pOrder->InstrumentID;
        order.price = pOrder->LimitPrice;
        order.quantity = pOrder->VolumeTotalOriginal;
        
        // 转换订单状�?
        switch (pOrder->OrderStatus) {
            case THOST_FTDC_OST_AllTraded:
                order.status = OrderStatus::FILLED;
                break;
            case THOST_FTDC_OST_PartTradedQueueing:
                order.status = OrderStatus::PARTIALLY_FILLED;
                break;
            case THOST_FTDC_OST_NoTradeQueueing:
                order.status = OrderStatus::NEW;
                break;
            case THOST_FTDC_OST_Canceled:
                order.status = OrderStatus::CANCELLED;
                break;
            default:
                order.status = OrderStatus::REJECTED;
                break;
        }

        handler_->onOrder(order);
    }

    void OnRtnTrade(CThostFtdcTradeField* pTrade) override {
        if (!pTrade) return;

        Trade trade;
        trade.order_id = pTrade->OrderRef;
        trade.symbol = pTrade->InstrumentID;
        trade.price = pTrade->Price;
        trade.quantity = pTrade->Volume;
        trade.timestamp = std::chrono::system_clock::now();

        handler_->onTrade(trade);
    }

    void OnRspError(CThostFtdcRspInfoField* pRspInfo, int nRequestID, bool bIsLast) override {
        if (pRspInfo) {
            handler_->onError(pRspInfo->ErrorID, pRspInfo->ErrorMsg);
        }
    }

private:
    CTPTraderHandler* handler_;
};

// CTP行情处理�?
class CTPMarketDataHandler : public CThostFtdcMdSpi {
public:
    CTPMarketDataHandler(
        const std::string& front_address,
        const std::string& broker_id,
        const std::string& user_id,
        const std::string& password,
        const std::string& app_id,
        const std::string& auth_code
    );

    ~CTPMarketDataHandler();

    // 连接CTP
    bool connect();
    
    // 断开连接
    void disconnect();

    // 订阅行情
    bool subscribeMarketData(const std::vector<std::string>& instruments);

    // 取消订阅
    bool unsubscribeMarketData(const std::vector<std::string>& instruments);

    // 设置行情回调
    void setMarketDataCallback(std::function<void(const MarketDataMessage&)> callback);

    // CTP回调接口实现
    void OnFrontConnected() override;
    void OnFrontDisconnected(int nReason) override;
    void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspUnSubMarketData(CThostFtdcSpecificInstrumentField *pSpecificInstrument, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRtnDepthMarketData(CThostFtdcDepthMarketDataField *pDepthMarketData) override;

    // 回调方法
    void onConnected();
    void onDisconnected(int reason);
    void onLoginSuccess();
    void onLoginFailed(int error_code, const std::string& error_msg);
    void onMarketData(const MarketDataMessage& msg);
    void onError(int error_code, const std::string& error_msg);

private:
    CThostFtdcMdApi* api_;
    std::string front_address_;
    std::string broker_id_;
    std::string user_id_;
    std::string password_;
    std::string app_id_;
    std::string auth_code_;
    std::atomic<bool> connected_{false};
    std::function<void(const MarketDataMessage&)> market_data_callback_;
    std::mutex mutex_;
};

// CTP交易处理�?
class CTPTraderHandler : public CThostFtdcTraderSpi {
public:
    CTPTraderHandler(
        const std::string& front_address,
        const std::string& broker_id,
        const std::string& user_id,
        const std::string& password,
        const std::string& app_id,
        const std::string& auth_code
    );

    ~CTPTraderHandler();

    // 连接CTP
    bool connect();
    
    // 断开连接
    void disconnect();

    // 下单
    bool submitOrder(const Order& order);

    // 撤单
    bool cancelOrder(const std::string& order_id);

    // 查询持仓
    bool queryPosition();

    // 查询资金
    bool queryAccount();

    // 设置订单状态回�?
    void setOrderStatusCallback(std::function<void(const OrderStatus&)> callback);

    // 设置成交回调
    void setTradeCallback(std::function<void(const Trade&)> callback);

    // CTP回调接口实现
    void OnFrontConnected() override;
    void OnFrontDisconnected(int nReason) override;
    void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspError(CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRtnOrder(CThostFtdcOrderField *pOrder) override;
    void OnRtnTrade(CThostFtdcTradeField *pTrade) override;
    void OnRspQryInvestorPosition(CThostFtdcInvestorPositionField *pInvestorPosition, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;
    void OnRspQryTradingAccount(CThostFtdcTradingAccountField *pTradingAccount, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) override;

    // 回调方法
    void onConnected();
    void onDisconnected(int reason);
    void onLoginSuccess();
    void onLoginFailed(int error_code, const std::string& error_msg);
    void onOrder(const Order& order);
    void onTrade(const Trade& trade);
    void onError(int error_code, const std::string& error_msg);

private:
    CThostFtdcTraderApi* api_;
    std::string front_address_;
    std::string broker_id_;
    std::string user_id_;
    std::string password_;
    std::string app_id_;
    std::string auth_code_;
    std::atomic<bool> connected_{false};
    std::function<void(const OrderStatus&)> order_status_callback_;
    std::function<void(const Trade&)> trade_callback_;
    std::mutex mutex_;
};

// CTP接口�?
class CTPInterface {
public:
    explicit CTPInterface(const CTPConfig& config);
    ~CTPInterface();

    bool initialize();
    void cleanup();
    bool isConnected() const;
    std::string getLastError() const;

    std::shared_ptr<CTPMarketDataHandler> getMarketDataHandler() const;
    std::shared_ptr<CTPTraderHandler> getTraderHandler() const;

private:
    CTPConfig config_;
    std::shared_ptr<CTPMarketDataHandler> market_data_handler_;
    std::shared_ptr<CTPTraderHandler> trader_handler_;
    std::string last_error_;
    mutable std::mutex error_mutex_;
};

} // namespace hft 
